package com.ipay.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.sql.DataSource;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author ：前世小和尚（xiaopingzhang8@creditease.cn）
 * @Description ：创建线程池配置
 * @ClassName ：ThreadPoolConfig
 * @Company ：普信恒业科技发展（北京）有限公司
 * @date ：2018/4/12 15:51
 */
@Configuration
@ConfigurationProperties(prefix = "spring.threadpool")
public class ThreadPoolConfig {
    private static final Logger log = LoggerFactory.getLogger(ThreadPoolConfig.class);

    private int corePoolSize;
    private int maxPoolSize;
    private int queueCapacity;
    private Class<? extends RejectedExecutionHandler> reject;


    @Bean("executorService")
    ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        try {
            threadPoolTaskExecutor.setRejectedExecutionHandler(reject == null ? new ThreadPoolExecutor.AbortPolicy() : reject.newInstance());
        } catch (Exception e) {
            log.info("create reject strategy is failed", e);
            threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        }
        return threadPoolTaskExecutor;
    }

    public int getCorePoolSize() {
        return corePoolSize;
    }

    public void setCorePoolSize(int corePoolSize) {
        this.corePoolSize = corePoolSize;
    }

    public int getMaxPoolSize() {
        return maxPoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public int getQueueCapacity() {
        return queueCapacity;
    }

    public void setQueueCapacity(int queueCapacity) {
        this.queueCapacity = queueCapacity;
    }

    public Class<? extends RejectedExecutionHandler> getReject() {
        return reject;
    }

    public void setReject(Class<? extends RejectedExecutionHandler> reject) {
        this.reject = reject;
    }
}
